use colored::Colorize;
use tklog::LEVEL;
/**
黑色 30 \x1b[30m黑色文字\x1b[0m
红色 31 \x1b[31m红色文字\x1b[0m
绿色 32 \x1b[32m绿色文字\x1b[0m
黄色 33 \x1b[33m黄色文字\x1b[0m
蓝色 34 \x1b[34m蓝色文字\x1b[0m
品红 35 \x1b[35m品红文字\x1b[0m
青色 36 \x1b[36m青色文字\x1b[0m
白色 37 \x1b[37m白色文字\x1b[0m
 */

pub fn tklog_init(level: &str, console: bool, path: &str) {
    let level = match level.to_lowercase().as_str() {
        "trace" => LEVEL::Trace,
        "debug" => LEVEL::Debug,
        "info" => LEVEL::Info,
        "warn" => LEVEL::Warn,
        "error" => LEVEL::Warn,
        "off" => LEVEL::Off,
        _ => LEVEL::Debug,
    };
    use tklog::{handle::FileTimeMode, Format, LogOption, MODE};

    tklog::LOG
        .set_console(console)
        .set_level(level)
        .set_format(Format::LevelFlag | Format::Microseconds | Format::Date | Format::LongFileName)
        .set_cutmode_by_time(path, MODE::DAY, 365, true)
        .set_formatter("{time} {level} {file} => {message}\r\n")
        .set_mod_option(
            "sqlx_mysql::*",
            LogOption {
                level: Some(LEVEL::Off),
                console: Some(false),
                format: None,
                formatter: None,
                fileoption: None,
            },
        )
        .uselog()
        .set_attr_format(|fmt| {
            fmt.set_console_body_fmt(|level, body| {
                let thread_info = std::thread::current().id();
                match level {
                    LEVEL::Trace => format!("\x1b[1;37m[TRACE]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Debug => format!("\x1b[1;32m[DEBUG]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Info => format!("\x1b[1;34m[INFO ]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Warn => format!("\x1b[1;33m[WARN ]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Error => format!("\x1b[1;31m[ERROR]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Fatal => format!("\x1b[1;35m[FATAL]\x1b[0m [{:?}] {body}", thread_info),
                    LEVEL::Off => "".to_string(),
                }
            });
        });
}

#[tokio::main]
pub async fn main() -> anyhow::Result<()> {
    tklog_init("trace", true, "/tmp/logs/tklog_demo.log");

    log::trace!("{}", "trace");
    log::debug!("{}", "debug");
    log::info!("{}", "info");
    log::warn!("{}", "warn");
    log::error!("{}", "error");

    std::thread::sleep(std::time::Duration::from_secs(3));

    Ok(())
}
